/**
 * Created with JetBrains WebStorm.
 * User: Fred_974
 * Date: 14/06/13
 * Time: 11:16
 * To change this template use File | Settings | File Templates.
 */
var connector = require('./connector');
var connection = connector.connection();
// We need our model
var Plantation = require("./Plantation");


var persistPlantationSettings = function(plantation, callback){

    var post  = {type: plantation.type, growRate: plantation.growRate,
        decayTime: plantation.decayTime, seedPrice: plantation.seedPrice}



    if(plantation.id == null){

        connection.query('INSERT INTO plantation SET ?', post, function(err, rows, fields){

            if (err) throw err; // if there is an error we throw it
            callback(plantation); // Callback basicaly it's the end of the controleur
        });
    }else{
        connection.query('update plantation SET ? where id = ?',[post,plantation.id], function(err, rows, fields){



            if (err) throw err; // if there is an error we throw it
            callback(plantation); // Callback basicaly it's the end of the controleur
        });

    }


};

var getAll = function(callback){
    connection.query('select * from plantation', function(err, rows, fields){

        if (err) throw err; // if there is an error we throw it

        var plantations = new Array();

        for(var i = 0; i < rows.length; i++){
            var p = new Plantation();
            p.init(rows[i]);
            plantations.push(p);
        }

        callback(plantations); // Callback basicaly it's the end of the controleur
    });
}

var deletePlantation = function(plantation, callback){



    if(plantation.id == null){

        connection.query('delete from plantation where id ='+plantation.id, function(err, rows, fields){

            if (err) throw err; // if there is an error we throw it
            callback(plantation); // Callback basicaly it's the end of the controleur
        });
    }else{
        connection.query('delete from plantation where id ='+plantation.id, function(err, rows, fields){



            if (err) throw err; // if there is an error we throw it
            callback(plantation); // Callback basicaly it's the end of the controleur
        });

    }
}

exports.persistPlantationSettings = persistPlantationSettings;
exports.deletePlantation = deletePlantation;
exports.getAll = getAll;
